package com.wecan.base.metadata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liuzhihao
 * @Date 2022.01.21
 * @Version ${version}
 * @Description 权限数据工具
 */
public class PermissionUtils {
    public static final Map<Integer, PermissionTree> indexMap = new HashMap<>();

    public static List<PermissionTree> permissionTrees = new ArrayList<>();

    static {
        // 每一个parentMark对应的自己的孩子树
        Map<Integer, List<PermissionTree>> parentMap = new HashMap<>();
        // 未放入树中的权限树节点
        Map<Integer, PermissionTree> tempMap = new HashMap<>();
        for (Permission permission : Permission.values()) {
            PermissionTree permissionTree = new PermissionTree();
            indexMap.put(permission.getMark(), permissionTree);
            permissionTree.setMark(permission.getMark());
            permissionTree.setName(permission.getName());
            permissionTree.setParentMark(permission.getParentMark());
            permissionTree.setType(permission.getType());
            parentMap.put(permission.getMark(), permissionTree.getChildren());
            // 如果父权限为空则是最顶层节点记录下来
            if (permission.getParentMark() == null) {
                permissionTrees.add(permissionTree);
            } else {
                // 否则则通过当前权限的parentMark获取是否已经有父权限树存在
                List<PermissionTree> parentPermissionTree = parentMap.get(permission.getParentMark());
                PermissionTree permissionTree1 = indexMap.get(permission.getParentMark());
                // 如果存在则将当前的权限树连接起来
                if (parentPermissionTree != null) {
                    parentPermissionTree.add(permissionTree);
                    permissionTree1.setHasChildren(true);
                } else {
                    // 不存在则将当前权限树缓存起来,供以后将权限一次性插入
                    tempMap.put(permission.getMark(), permissionTree);
                }
            }
        }
        // 一次性将未插入的权限树连接到各个节点上
        for (PermissionTree permissionTree1: tempMap.values()) {
            Integer parentMark = permissionTree1.getParentMark();
            List<PermissionTree> parentPermissionTree = parentMap.get(parentMark);
            PermissionTree permissionTree = indexMap.get(parentMark);
            permissionTree.setHasChildren(true);
            parentPermissionTree.add(permissionTree1);
        }
    }
}
